<script setup lang="ts">
import UploadBook from '@/components/UploadBook.vue'
import HomeToolBar from '@/components/HomeToolBar.vue'
import FeedbackForm from '@/components/FeedbackForm.vue'
import useComponentRef from '@/hooks/useComponentRef'

import { db, type Book } from '@/db/db'
import { h, ref, watch, computed, type Component } from 'vue'
import { useMessage, NButton, NIcon } from 'naive-ui'
import {
  LightModeOutlined as LightIcon,
  NightlightOutlined as NightIcon,
  AddCircleOutlineFilled as AddIcon,
  FeedbackOutlined,
} from '@vicons/material'
import { useThemeStore } from '@/stores/themes'
import { ArrowOutlineUpRight48Regular, TextBulletListSquare24Regular } from '@vicons/fluent'
import { useRouter } from 'vue-router'

const loading = ref(true)
const message = useMessage()
/**
 * 菜单渲染
 */
const renderIcon = (icon: Component) => {
  return () => h(NIcon, null, () => h(icon))
}
const menuOptions = computed(() => [
  {
    label: myTheme.theme === 'light' ? '暗' : '亮',
    key: 'theme',
    icon: renderIcon(myTheme.theme === 'light' ? NightIcon : LightIcon),
  },
  {
    label: () => h(NButton, { 'render-icon': renderIcon(AddIcon), onClick: onShowUpload }, '添加书籍'),
    key: 'upload',
  },
])

const myTheme = useThemeStore()
const handleUpdateValue = (key: string) => {
  if (key !== 'upload') {
    myTheme.setTheme(myTheme.theme === 'light' ? 'dark' : 'light')
  }
}

const uploadRef = useComponentRef(UploadBook)
const onShowUpload = () => {
  if (uploadRef.value) {
    uploadRef.value.modalShow()
  }
}

/**
 * 加载书籍列表
 */
const orderBy = ref('name')
const books = ref<Book[]>([])
const loadBook = async (newVal: string) => {
  books.value = await db.books.orderBy(newVal).reverse().toArray()
  loading.value = false
}
watch(
  orderBy,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      loading.value = true
      loadBook(newVal)
    }
  },
  { immediate: true },
)

const onSortChange = (e: string) => {
  orderBy.value = e
}

const onUploadFinish = () => {
  loading.value = true
  loadBook(orderBy.value)
}

const { push } = useRouter()
const onRenderTracked = (id: string) => {
  push({ name: 'reader', params: { id } })
}

const chooseing = ref(false)
const checkboxList = ref<string[]>([])
const onDel = async () => {
  if (checkboxList.value.length) {
    try {
      const deletedCount = await db.books.where('id').anyOf(checkboxList.value).delete()
      message.info(`成功删除了${deletedCount}条记录`)
      loadBook(orderBy.value)
    } catch (err) {
      message.error(`删除失败 ${err}`)
    }
  } else {
    message.warning('请先勾选项')
  }
}
const isFeedback = ref(false)

const onAbout = () => {
  push({ name: 'about' })
}
</script>

<template>
  <n-layout id="uploadModalTo">
    <n-layout-content content-style="padding: 24px;min-height:100vh">
      <!-- header -->
      <header>
        <n-flex justify="space-between">
          <n-flex align="center" style="cursor: pointer">
            <img src="@/assets/RF.png" style="width: 40px; height: 40px" />
            <span style="font-size: 24px">Reader Farm</span>
          </n-flex>
          <div>
            <n-menu mode="horizontal" :options="menuOptions" responsive @update:value="handleUpdateValue" />
          </div>
        </n-flex>
      </header>
      <n-divider />

      <!-- tools -->
      <n-flex v-if="books?.length" justify="flex-end" class="tool-bar">
        <home-tool-bar :chooseing="chooseing" @change="onSortChange" @pick="chooseing = !chooseing" @del="onDel" />
      </n-flex>

      <!-- books -->
      <n-checkbox-group v-model:value="checkboxList">
        <n-grid x-gap="30" y-gap="50" cols="2 s:3 m:4 l:4 xl:6 2xl:7" responsive="screen">
          <n-gi v-for="book in books" :key="book.id">
            <n-skeleton v-if="loading" height="300px"></n-skeleton>
            <template v-else>
              <n-flex v-show="chooseing" justify="flex-end" style="padding-bottom: 5px">
                <n-checkbox :value="book.id" size="large" />
              </n-flex>
              <n-card hoverable embedded @click="onRenderTracked(book.id)" content-style="border-radius:30px">
                <template #cover>
                  <img :src="book.cover || ''" alt="封面" class="cover-img" />
                </template>
                <div style="margin-top: 20px">
                  <n-ellipsis :line-clamp="2"> {{ book.name }}</n-ellipsis>
                </div>
              </n-card>
            </template>
          </n-gi>
        </n-grid>
      </n-checkbox-group>

      <!-- empty -->
      <div class="empty" v-if="!books?.length && !loading">
        <div class="go-add">
          <n-icon size="60">
            <ArrowOutlineUpRight48Regular />
          </n-icon>
        </div>
        <n-h1 v-for="value in 'KONG!'" :key="value">
          {{ value }}
        </n-h1>
      </div>

      <!-- 反馈 -->
      <FeedbackForm v-if="isFeedback" @close="isFeedback = false" class="feedback-form-card" />
      <n-float-button v-show="!isFeedback" position="fixed" :bottom="90" :right="30" type="primary"
        @click="isFeedback = !isFeedback">
        <n-tooltip trigger="hover" placement="right">
          <template #trigger>
            <n-icon>
              <FeedbackOutlined />
            </n-icon>
          </template>
          反馈/建议
        </n-tooltip>
      </n-float-button>

      <!-- about -->
      <n-float-button position="fixed" :bottom="30" :right="30" type="primary" @click="onAbout">
        <n-tooltip trigger="hover" placement="right">
          <template #trigger>
            <n-icon>
              <TextBulletListSquare24Regular />
            </n-icon>
          </template>
          关于本站
        </n-tooltip>
      </n-float-button>
    </n-layout-content>
  </n-layout>
  <UploadBook ref="uploadRef" @finish="onUploadFinish" />
</template>

<style scoped>
.n-menu.n-menu--horizontal .n-menu-item-content {
  padding: 0;
}

.n-card {
  cursor: pointer;
  padding: 10px;
  padding-bottom: 0;
  height: 100%;
  max-width: 300px;
}

.go-add {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  padding-right: 120px;
  padding-bottom: 50px;
}

.cover-img {
  object-fit: cover;
  transform: scale(1);
  transition: transform 0.3s ease;
}

.cover-img:hover {
  transform: scale(1.05);
}

.tool-bar {
  margin-bottom: 20px;
  margin-right: 20px;
}

.container {
  padding: 40px 6%;
}

.empty {
  margin: 30px 0;
}

.n-h1 {
  text-align: center;
  font-style: italic;
}

.feedback-form-card {
  z-index: 999;
  position: fixed;
  bottom: 30px;
  right: 30px;
  height: 400px;
}
</style>
